﻿/// <reference path="../Core.js" />

IM.Utility.Hashtable = function() {
    this.Keys = []; //hashtable的key集合
    this.Values = []; //hashtable的值集合

    this.Add = function(key, value) {
        if (typeof key != "undefined" && typeof value != "undefined") {

            if (this.Find(key) != null) {
                throw new Error("已经存在相同key");
            }
            this.Keys.push(key);
            this.Values.push(value);
        }
    };

    this.Remove = function(key) {
        var index = -1;
        for (var i = 0; i < this.Keys.length; i++) {
            if (this.Keys[i] == key) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            for (var i = index; i < this.Keys.length - 1; i++) {
                this.Keys[i] = this.Keys[i + 1];
                this.Values[i] = this.Values[i + 1];
            }
            this.Keys.pop();
            this.Values.pop();
        }
    };

    this.Find = function(key) {
        var value = null;
        for (var i = 0; i < this.Keys.length; i++) {
            if (this.Keys[i] == key) {
                value = this.Values[i];
                break;
            }
        }
        return value;
    };

    this.Clear = function() {
        this.Keys = [];
        this.Values = [];
    };

    this.Count = function() {
        return this.Keys.length;
    };

    //用指定方法对每一对key value进行处理,fun要有参数 (key , value)
    this.Each = function(fun) {
        for (var i = 0; i < this.Keys.length; i++) {
            if (fun)
                fun(this.Keys[i], this.Values[i]);
        }
    };
};